package org.lyl.taobao.controller;

import org.lyl.taobao.api.IUserService;
import org.lyl.taobao.api.entity.User;
import org.lyl.taobao.service.UserServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author: Re
 * @Date: 2021/3/26 19:24
 */
@WebServlet("/login")
public class InsertUserServlet extends HttpServlet {
    private static final Logger logger = LoggerFactory.getLogger(InsertUserServlet.class);
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;utf-8");
        String userName = req.getParameter("userName");
        String userPassword = req.getParameter("userPassword");
        if (userName == null || "".equals(userName.trim())){
            req.setAttribute("msg","用户名不能为空");
            req.getRequestDispatcher("login.jsp").forward(req,resp);
            return;
        }
        if (userPassword == null || "".equals(userPassword)){
            req.setAttribute("msg","用户密码不能为空");
            req.getRequestDispatcher("login.jsp").forward(req,resp);
            return;
        }
        User user = new User(userName,userPassword,0,"1");
        logger.info(user.toString());
        IUserService iUserService=new UserServiceImpl();
        if (iUserService.registerUser(user) != null) {
            req.setAttribute("msg","用户已存在");
            req.getRequestDispatcher("login.jsp").forward(req,resp);
            return;
        }
        boolean judgment=iUserService.insertUser(user);
        if (judgment){
            req.setAttribute("msg",user);
            req.getRequestDispatcher("successUser.jsp").forward(req,resp);
        }else {
            req.setAttribute("msg","失败");
            req.getRequestDispatcher("login.jsp").forward(req,resp);
        }
    }
}
